<template>
  <a-drawer
    :title="title"
    :width="$store.getters.isMobile ? 350 : 800"
    :visible="visible"
    :body-style="{
      paddingBottom: '80px',
      height: 'calc(100% - 110px)',
      boxSizing: 'border-box',
      overflow: 'auto',
      paddingTop: '0px',
    }"
    :maskClosable="false"
    @close="onClose"
  >
    <a-tabs v-model:activeKey="activeKey">
      <a-tab-pane v-for="tab of tabList" :key="tab.key" :tab="tab.title" />
    </a-tabs>
    <a-form
      :model="form"
      :rules="rules"
      layout="vertical"
      style="padding-top: 10px"
    >
      <a-row :gutter="16" :wrap="true" v-show="activeKey == 'basic'">
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item v-bind="validateInfos.village_id">
            <template #label>
              <span>{{ $L("项目") }}</span>
            </template>
            <a-select
              :placeholder="placeholderVillage"
              v-model:value="form.village_id"
              @change="(value) => changeVillageId(value)"
            >
              <a-select-option
                :value="project.id"
                :key="project.id"
                v-for="project of projectList"
              >
                {{ project.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item v-bind="validateInfos.build_id">
            <template #label>
              <span>{{ $L("楼宇") }}</span>
            </template>
            <a-select
              :placeholder="placeholderBuild"
              v-model:value="form.build_id"
              @change="changeBuilding"
            >
              <a-select-option
                :value="building.id"
                :key="building.id"
                v-for="building of buildingList"
              >
                {{ building.build_name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item label="楼层" v-bind="validateInfos.layer_id">
            <a-select placeholder="请选择楼层" v-model:value="form.layer_id">
              <a-select-option
                :value="floor.id"
                :key="floor.id"
                v-for="floor of floorList"
              >
                {{ floor.layer_name }}
              </a-select-option>
              <template #dropdownRender="{ menuNode: menu }">
                <v-nodes :vnodes="menu" />
                <a-divider style="margin: 4px 0" />

                <!--@mousedown="e => e.preventDefault()"  -->
                <div
                  style="
                    padding: 4px 8px;
                    cursor: pointer;
                    color: #1890ff;
                    text-align: center;
                  "
                  @mousedown="(e) => e.preventDefault()"
                  @click="addLayer"
                >
                  添加
                </div>
              </template>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item
            label="房号"
            name="room_name"
            v-bind="validateInfos.room_name"
          >
            <a-input v-model:value="form.room_name" placeholder="请输入房号" />
          </a-form-item>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item name="room_number" v-bind="validateInfos.room_number">
            <template #label>
              <span>房间数字编号</span>
              <text-tip
                :tips="[
                  '用于房间列表进行排序，以及未来智能设备等第三方对接使用',
                  '数字编号不能超过10位',
                ]"
                :showNo="false"
              />
            </template>
            <a-input
              v-model:value="form.room_number"
              placeholder="请输入数字编号"
              type="number"
            />
          </a-form-item>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item
            name="room_alias_id"
            v-bind="validateInfos.room_alias_id"
          >
            <template #label>
              <span>房源管理编号</span>
              <text-tip
                :tips="[
                  '用于收银台快捷搜索房源，例如使用项目编号-楼宇编号-楼层编号-房间编号',
                ]"
                :showNo="false"
              />
            </template>
            <a-input
              v-model:value="form.room_alias_id"
              placeholder="请输入房源管理编号"
            />
          </a-form-item>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item
            label="建筑面积"
            name="build_area"
            v-bind="validateInfos.build_area"
          >
            <a-input
              v-model:value="form.build_area"
              placeholder="请输入建筑面积"
              suffix="㎡"
            />
          </a-form-item>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item name="rental_area" v-bind="validateInfos.rental_area">
            <template #label>
              <span>{{ $L("计租面积") }}</span>
              <text-tip :tips="['用于合同计算租金的面积']" :showNo="false" />
            </template>
            <a-input
              v-model:value="form.rental_area"
              placeholder="请输入计租面积"
              suffix="㎡"
              @blur="onRentalAreaBlur"
            />
          </a-form-item>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item
            name="charging_area"
            v-bind="validateInfos.charging_area"
          >
            <template #label>
              <span>计费面积</span>
              <text-tip
                :tips="['用于合同计算物业费的面积，若为空则取计租面积']"
                :showNo="false"
              />
            </template>
            <a-input
              v-model:value="form.charging_area"
              placeholder="请输入计费面积"
              suffix="㎡"
            />
          </a-form-item>
        </a-col>
     
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item
            label="套内面积"
            name="InsideArea"
            v-bind="validateInfos.inside_area"
          >
            <a-input
              v-model:value="form.inside_area"
              placeholder="请输入套内面积"
              suffix="㎡"
            />
          </a-form-item>
        </a-col>
 
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item name="is_unreal" v-bind="validateInfos.is_unreal">
            <template #label>
              <span>{{ "虚拟" + $L("房源") }}</span>
              <text-tip
                :tips="['不占用房屋面积统计、不占用计租率。']"
                :showNo="false"
              />
            </template>
            <a-select
              :options="isUnrealOptions"
              v-model:value="form.is_unreal"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item name="is_unreal" v-bind="validateInfos.is_unreal">
            <template #label>
              <span>{{ $L("房源") + "交付时间" }}</span>
              <!-- <text-tip
                :tips="['不占用房屋面积统计、不占用计租率。']"
                :showNo="false"
              /> -->
            </template>
            <a-date-picker
              style="width: 100%"
              v-model:value="form.deliver_time"
              valueFormat="YYYY-MM-DD"
            />
          </a-form-item>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item name="proprietor" label="绑定业主">
            <TenantComponent
                :ownerId="form.landlord_id"
                :allowes="true"
                :titleser="'绑定业主'"
                @selectcancel="Selectcancel"
                @changeallowes="changeallowes"
                @request="$utils.commonRequest"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <!-- 第二部分 -->
      <a-row :gutter="16" :wrap="true" v-show="activeKey == 'invitation'">
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item
            label="产权性质"
            name="property_right"
            v-bind="validateInfos.property_right"
          >
            <a-select
              placeholder="请选择产权性质"
              v-model:value="form.property_right"
            >
              <a-select-option
                :value="property.value"
                :key="property.value"
                v-for="property of propertyRightList"
              >
                {{ property.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item label="租赁状态" name="invitation_status_txt">
            <a-input
              v-model:value="form.room_status_txt"
              placeholder="租赁状态"
              :disabled="true"
            />
          </a-form-item>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item label="招商状态" name="invitation_status">
            <a-select
              v-model:value="form.invitation_status"
              placeholder="招商状态"
              :options="invitationOption"
            />
          </a-form-item>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item label="可租日期" name="lease_end">
            <a-date-picker
              style="width: 100%"
              v-model:value="form.lease_end"
              valueFormat="YYYY-MM-DD"
              :inputReadOnly="true"
            />
          </a-form-item>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item label="装修情况" name="decoration">
            <a-select
              placeholder="请选择装修情况"
              v-model:value="form.decoration"
            >
              <a-select-option
                :value="decoration.value"
                :key="decoration.value"
                v-for="decoration of DecorationList"
              >
                {{ decoration.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item name="ListingStatus">
            <template #label>
              <span>{{ $L("房源") }}状态</span>
            </template>
            <a-select
              :placeholder="ListingStatusName"
              v-model:value="form.status"
            >
              <a-select-option
                :value="ListingStatus.value"
                :key="ListingStatus.value"
                v-for="ListingStatus of ListingStatusList"
              >
                {{ ListingStatus.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item name="house_type">
            <template #label>
              <span>{{ $L("房源") }}类型</span>
            </template>
            <a-select
              :placeholder="house_type_name"
              v-model:value="form.house_type"
            >
              <a-select-option
                :value="HouseType.value"
                :key="HouseType.value"
                v-for="HouseType of HouseTypeList"
              >
                {{ HouseType.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <!-- 第三部分 -->
      <a-row :gutter="16" :wrap="true" v-show="activeKey == 'invitation'">
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item :label="$L('报价')" name="pre_unit_price">
            <a-input
              v-model:value="form.pre_unit_price"
              :placeholder="dictName"
            >
              <template #addonAfter>
                <a-select
                  v-model:value="form.price_unit"
                  :options="contractPriceUnitArr"
                  style="width: 96px"
                />
              </template>
            </a-input>
          </a-form-item>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item label="底价" name="pre_unit_price_min">
            <a-input
              v-model:value="form.pre_unit_price_min"
              placeholder="请输入底价"
            >
              <template #addonAfter>
                <a-select
                  v-model:value="form.price_unit_min"
                  :options="contractPriceUnitArr"
                  style="width: 96px"
                />
              </template>
            </a-input>
          </a-form-item>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item name="record_no">
            <template #label>
              <span>{{ $L("房源") }}备案号</span>
            </template>
            <a-input
              v-model:value="form.record_no"
              :placeholder="record_no_name"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16" v-show="activeKey == 'invitation'">
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item name="floor_height">
            <template #label>
              <span>层高</span>
              <text-tip :tips="['单位：m']" :showNo="false" />
            </template>
            <a-input
              type="number"
              v-model:value="form.floor_height"
              placeholder="请输入层高"
            />
          </a-form-item>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item label="荷载值" name="load_max">
            <a-input v-model:value="form.load_max" placeholder="请输入荷载值" />
          </a-form-item>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item label="标签" name="tag_arr">
            <a-select
              v-model:value="tag_id_arr"
              :options="industryOptions"
              mode="multiple"
              placeholder="请选择标签"
            >
              <template #dropdownRender="{ menuNode: menu }">
                <v-nodes :vnodes="menu" />
                <a-divider style="margin: 4px 0" />

                <!--@mousedown="e => e.preventDefault()"  -->
                <div
                  style="
                    padding: 4px 8px;
                    cursor: pointer;
                    color: #1890ff;
                    text-align: center;
                  "
                  @mousedown="(e) => e.preventDefault()"
                  @click="addTag"
                >
                  <!-- <plus-outlined /> -->
                  添加
                </div>
              </template>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16" v-show="activeKey == 'invitation'">
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item>
            <template #label>
              <span>{{ $L("房源") }}招商编号</span>
            </template>
            <a-input
              v-model:value="form.extra_config.investmentNumber"
              :placeholder="placeholderNumber"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item>
            <template #label>
              <span>图片</span>
              <text-tip :tips="['建议上传16：9的图片']" :showNo="false" />
            </template>
            <image-cropper
              ref="imageCropperList"
              :options="cropperOptions"
              @crop-upload-success="cropSuccessImage"
              @remove="removeImageList"
              :imageNumber="6"
              :imageFileList="true"
            />
            <!-- <a-upload
              :action="$utils.imgAction"
              :headers="{ 'org-token': $store.getters.token }"
              :multiple="false"
              v-model:file-list="fileList"
              @change="handleUploadChange"
              name="image"
              :data="{ dir: 'org_village_building' }"
              accept="image/jpg,image/jpeg,image/gif,image/png"
              list-type="picture-card"
            >
              <div v-if="fileList.length < 3">
                <PlusOutlined />
                <div style="padding-top: 4px">上传</div>
              </div>
            </a-upload> -->
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item>
            <template #label>
              <span>招商条件</span>
            </template>
            <a-textarea
              v-model:value="form.investment_conditions"
              placeholder="请输入招商条件"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item>
            <template #label>
              <span>招商政策</span>
            </template>
            <vue-ueditor-wrap
              @ready="ready"
              v-model="form.investment_policy"
              :config="ueditorEditorConfig"
              :editor-id="'edit_id_' + edit_id"
            ></vue-ueditor-wrap>
          </a-form-item>
        </a-col>
      </a-row>
      <!-- 第四部分 -->
      <a-row :gutter="16" v-show="activeKey == 'expend'">
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item label="使用率">
            <a-input
              v-model:value="form.extra_config.utilization"
              placeholder="请输入实用率"
            />
          </a-form-item>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item label="办公格局">
            <a-input
              v-model:value="form.extra_config.officePattern"
              placeholder="例如： 2+1"
            />
          </a-form-item>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item label="窗面朝向">
            <a-input
              v-model:value="form.extra_config.windowFaceOrientation"
              placeholder="例如： 南"
            />
          </a-form-item>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item label="免租期">
            <a-input
              v-model:value="form.extra_config.rentFree"
              placeholder="例如： 前2个月"
            />
          </a-form-item>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item label="最短租期">
            <a-input
              v-model:value="form.extra_config.minLeaseTerm"
              placeholder="例如： 12个月"
            />
          </a-form-item>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item name="pre_unit_price">
            <template #label>
              <span>排序值</span>
              <text-tip :tips="['用于招商平台的展示优先级']" :showNo="false" />
            </template>
            <a-input-number
              style="width: 100%"
              id="inputNumber"
              :min="0"
              :precision="0"
              v-model:value="form.sort"
              placeholder="排序值越大展示越靠前"
            />
          </a-form-item>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item label="工位数量" name="pre_unit_price">
            <a-input-number
              style="width: 45%"
              id="inputNumber"
              :min="0"
              :precision="0"
              v-model:value="form.extra_config.station_number_min"
            />
            <span style="padding: 0 8px">-</span>
            <a-form-item-rest>
              <a-input-number
                style="width: 45%"
                id="inputNumber"
                :min="0"
                :precision="0"
                v-model:value="form.extra_config.station_number_max"
              />
            </a-form-item-rest>
          </a-form-item>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item name="pre_unit_price">
            <template #label>
              <span>VR链接</span>
              <text-tip :tips="['输入后默认支持VR展示']" :showNo="false" />
            </template>
            <a-input v-model:value="form.vr_link" />
          </a-form-item>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 24 : 8">
          <a-form-item label="户型图说明" name="pre_unit_price">
            <a-input v-model:value="form.extra_config.houseDescription" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item name="pre_unit_price">
            <template #label>
              <span>户型图</span>
              <text-tip :tips="['建议上传16:9的图片']" :showNo="false" />
            </template>
            <image-cropper
              ref="imageCropper"
              :options="cropperOptions"
              @crop-upload-success="cropSuccess"
              @remove="removeImage"
              :imageNumber="1"
              :imageFileList="true"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="上传视频">
            <a-upload
              v-model:file-list="fileListVideo"
              name="file"
              :multiple="false"
              :action="$utils.fileAction"
              :headers="{ 'org-token': $store.getters.token }"
              @change="handleChange"
              :before-upload="beforeUpload"
              accept="video/mp4"
            >
              <a-button>
                <UploadOutlined />
                上传文件
              </a-button>
              <div class="Video">支持上传10M以内的mp4格式的视频</div>
            </a-upload>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <div class="drawer-footer">
      <a-button class="mr-10" @click="onClose()">取消</a-button>
      <a-button type="primary" @click="onSubmit">提交</a-button>
    </div>

    <!-- 房源标签 -->
    <EditTag
      @closeTag="editTagClose"
      @success="editSuccess"
      :visible="editVisible"
    ></EditTag>

    <!-- 选择楼层 -->
    <layer-edit
      :visible="layerEditVisible"
      :content="layerContent"
      @cancel="layerEditVisible = false"
      @success="handleLayerEditSuccess"
    />
  </a-drawer>
</template>
<script>
import {
  defineComponent,
  reactive,
  ref,
  watch,
  toRaw,
  computed,
  toRefs,
  onBeforeUnmount,
  onMounted,
} from "vue";
import { Form, message } from "ant-design-vue";
import { DiffFilled, UploadOutlined } from "@ant-design/icons-vue";
import request from "../../../../common/utils/request";
import utils from "../../../../common/utils/utils";
import EditTag from "./EditTag.vue";
import ImageCropper from "../../../../components/ImageCropper/index.vue";
import BLCOMMON, { TextTip , TenantComponent } from "bl-common-vue3";
import LayerEdit from "../../BuildingManage/modules/LayerEdit.vue";
import store from "../../../../store";
import { VueUeditorWrap } from "vue-ueditor-wrap";
const useForm = Form.useForm;

export default defineComponent({
  name: "AddHouse",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [String, Number],
      default: 0,
    },
    villageId: {
      type: [String, Number],
      default: 0,
    },
    buildId: {
      type: [String, Number],
      default: 0,
    },
    layerId: {
      type: [String, Number],
      default: 0,
    },
    roomID: {
      type: [String, Number],
      default: 0,
    },
  },
  components: {
    DiffFilled,
    TextTip,
    EditTag,
    UploadOutlined,
    VNodes: (_, { attrs }) => {
      return attrs.vnodes;
    },
    ImageCropper,
    LayerEdit,
    VueUeditorWrap,
    TenantComponent
  },

  setup(props, context) {
    const title = computed(() => {
      return props.id
        ? `编辑${BLCOMMON.utils.L("房源")}`
        : `新增${BLCOMMON.utils.L("房源")}`;
    });
    const villageType = computed(() => store.getters.buildingInfo.villageType);

    const tag_id_arr = ref([]);
    // 表单
    const form = reactive({
      village_id: undefined,
      build_id: undefined,
      layer_id: undefined,
      room_name: "",
      rental_area: "",
      MinDivisibleArea: "",
      MaxContinuousArea: "",
      charging_area: "",
      build_area: "",
      inside_area: "",
      property_right: "",
      lease_end: "",
      decoration: undefined,
      ListingStatus: undefined,
      house_type: undefined,
      PracticalRate: "",
      pre_unit_price: "",
      pre_unit_price_min: "",
      price_unit: "",
      price_unit_min: "",
      SpecialPriceTime: "",
      record_no: "",
      floor_height: "",
      load_max: "",
      investmentNumber: "",
      status: 1,
      room_status_txt: "待租",
      invitation_status: undefined,
      tag_id_arr: [],
      room_number: "",
      vr_link: "",
      extra_config: {
        utilization: "",
        officePattern: "",
        windowFaceOrientation: "",
        rentFree: "",
        minLeaseTerm: "",
        sort: "",
        station_number_min: "",
        station_number_max: "",
        houseDescription: "",
        house: "",
        investmentNumber: "",
        investment_conditions: "",
        investment_policy: "",
      },
      room_alias_id: "",
      is_unreal: 0, //是否虚拟房源
      deliver_time: "", //交付时间
      landlord_id: undefined,
    });

    const numberRule = [
      {
        validator: (rules, value) => utils.numberValidator(rules, value),
        trigger: "change",
      },
    ];
    const rules = {
      village_id: [
        {
          required: true,
          message: "必填项",
        },
      ],
      build_id: [
        {
          required: true,
          message: "必填项",
        },
      ],
      layer_id: [
        {
          required: true,
          message: "必填项",
        },
      ],
      room_name: [
        {
          required: true,
          // validator: (rules, value) => utils.numberValidator(rules, value),
          message: "必填项",
        },
      ],
      room_number: [
        {
          required: true,
          message: "必填项",
        },
      ],
      rental_area: [
        {
          required: true,
          validator: (rules, value) => utils.numberValidator(rules, value),
          trigger: "change",
          type: "object",
        },
      ],
      build_area: [
        {
          required: true,
          // validator: (rules, value) => utils.numberValidator(rules, value),
          message: "必填项",
        },
      ],
      MinDivisibleArea: numberRule,
      MaxContinuousArea: numberRule,
      BillingArea: numberRule,
      BuiltupArea: numberRule,
      InsideArea: numberRule,
      pre_unit_price: numberRule,
      pre_unit_price_min: numberRule,
      FloorPrice: numberRule,
      FloorHeight: numberRule,
      LoadValue: numberRule,
    };
    //表单下拉选择数据
    // 项目
    const projectList = ref([]);
    const getProjectList = () => {
      const params = {};
      if (!props.id) {
        params.checked = 1;
      }
      request.get("/org", "/build/villageAndBuildList", params).then((res) => {
        projectList.value = res.villageList;
        console.log(projectList.value, "projectList.value");
        if (props.id) {
          changeVillageId(form.village_id, true);
        } else if (props.villageId) {
          form.village_id = props.villageId;
          changeVillageId(form.village_id, true);
        } else {
          if (res.villageList.length && form.village_id == undefined) {
            form.village_id = res.villageList[0].id;
            changeVillageId(form.village_id, true);
          }
        }
      });
    };
    // 楼层
    const floorList = ref([]);
    const getFloor = (id) => {
      request
        .get("/village", "/project/layer/all", {
          build_id: id,
        })
        .then((res) => {
          floorList.value = res.list;
          if (props.id) {
            floorList.value = res.list;
            return;
          } else if (props.layerId) {
            form.layer_id = props.layerId;
            return;
          }

          if (floorList.value.length) {
            form.layer_id = res.list[0].id;
            return;
          }
          if (!floorList.value.length) {
            form.layer_id = undefined;
            return;
          }
          // if (props.id) {
          //   //form.layer_id.value = form.layer_id;
          // } else {
          //   console.log("form.layer_id", form.layer_id);
          //   if (res.list.length && form.layer_id == undefined) {
          //     form.layer_id = res.list[0].id;
          //   }
          // }
        });
    };
    // 选择项目 获取楼宇
    const buildingList = ref([]);
    let buildingObj = {};
    const changeVillageId = (val, init = false) => {
      if (props.id) {
        buildingObj = projectList.value.find((item) => val == item.id);
        if (buildingObj && buildingObj.buildList) {
          buildingList.value = toRaw(buildingObj.buildList);
        }

        if (!init) {
          form.build_id = undefined;
          form.layer_id = undefined;
        }
        return;
      } else if (props.villageId) {
        buildingObj = projectList.value.find((item) => val == item.id);
        buildingList.value = toRaw(buildingObj.buildList);
        form.build_id = props.buildId;
        getFloor(form.build_id);
      } else {
        buildingObj = projectList.value.find((item) => val == item.id);
        buildingList.value = toRaw(buildingObj.buildList);
        form.build_id = buildingList.value[0].id;
        form.layer_id = undefined;

        getFloor(form.build_id);
      }
    };
    // 选择楼宇
    const changeBuilding = (val) => {
      console.log("选择的值", val);
      form.layer_id = undefined;
      getFloor(val);
    };
    const { resetFields, validate, validateInfos } = useForm(form, rules);
    const onCancel = () => {
      context.emit("success");
    };
    // 房间字段
    const DecorationList = ref([]);
    const HouseTypeList = ref([]);
    const propertyRightList = ref([]);
    const ListingStatusList = ref([]);
    const contractPriceUnitArr = ref([]);
    const getDecoration = (id) => {
      request.get("/village", "/project/room/type").then((res) => {
        contractPriceUnitArr.value = res.contractPriceUnitArr
          .filter((item) => {
            if (store.getters.orgInfo.paymentByRooms) {
              return (
                item.value !== "square_day" && item.value !== "square_month"
              );
            } else {
              return item;
            }
          })
          .map((item) => {
            return {
              label: item.name,
              value: item.value,
            };
          });
        if (!props.id) {
          form.price_unit = contractPriceUnitArr.value[0].value;
          form.price_unit_min = contractPriceUnitArr.value[0].value;
        }

        if (res.decorationList.length && form.Decoration == undefined) {
          form.Decoration = res.decorationList[0].value;
        }
        if (props.id) {
          DecorationList.value = res.decorationList;
          HouseTypeList.value = res.houseTypeArr;
          propertyRightList.value = res.propertyRight;
          ListingStatusList.value = res.roomStatusArr;
          return;
        }
        DecorationList.value = res.decorationList;
        HouseTypeList.value = res.houseTypeArr;
        propertyRightList.value = res.propertyRight;
        ListingStatusList.value = res.roomStatusArr;
        form.decoration = res.decorationList[0].value;
        if (villageType.value === "village") {
          form.house_type =
            res.houseTypeArr.filter((v) => v.value === "home")[0]?.value ||
            res.houseTypeArr[0].value;
        } else {
          form.house_type = res.houseTypeArr[0].value;
        }
        form.property_right = res.propertyRight[0].value;
      });
    };

    let tagArrState = {};
    const tagArrChange = (key, option) => {
      tagArrState[key] = option.id;
      console.log(option.id);
    };

    // 取消 和 提交表单
    const imageCropperList = ref(null);
    const imageCropper = ref(null);
    const onClose = () => {
      context.emit("cancel");
      add.value = 0;
      form.promoter_money_unit = "";
      form.promoter_money = "";
      imageCropper.value.clearImage();
      imageCropperList.value.clearImage();
    };
    const onSubmit = () => {
      // 图片上传筛选
      // let set = new Set();
      // images.forEach((item) => set.add(item));
      // let a = Array.from(set);

      // add.value = 0;

      validate().then(() => {
        let params = { ...toRaw(form), needMsg: true };
        // let params = JSON.parse(JSON.stringify(form));

        // console.log("-----params", params);
        const success = (res) => {
          message.success(res.msg || "保存成功！");
          context.emit("success");
          form.promoter_money_unit = "";
          form.promoter_money = "";
          onClose();
        };
        params.tag_id_arr = tag_id_arr.value;
        params.images = images;
        if (props.id) {
          params.id = props.id;
          // params.room_number = form.houseResource;
          request
            .put("/village", "/project/room", params)
            .then((res) => success(res));
        } else {
          request
            .post("/village", "/project/room", params)
            .then((res) => success(res));
        }
      });
    };

    // 获取详情
    let detail = {};
    const getDetail = () => {
      request
        .get("/village", "/project/room/get", {
          id: props.id,
          village_id: props.villageId,
        })
        .then((res) => {
          if (!res.detail.extra_config) {
            res.detail.extra_config = {};
          }
          detail = res.detail;

          setModelRef(detail);
          tag_id_arr.value = detail.tag_id_arr || [];
          form.village_id = detail.village_id;
          form.build_id = detail.build_id;
          form.invitation_status = detail.invitation_status;
          getFloor(form.build_id);
          if (detail.extra_config && detail.extra_config.house) {
            if (props.visible) {
              imageCropper.value.detailsImage([detail.extra_config.house]);
            }
          }
          if (detail.video) {
            fileListVideo.value = [
              {
                uid: "1",
                name: detail.video,
                status: "done",
                url: detail.video,
              },
            ];
            form.video = detail.video;
          }
          if (detail.images && detail.images.length > 0) {
            if (props.visible) {
              imageCropperList.value.detailsImage(detail.images);
            }
            images = detail.images;
          }

          form.layer_id = detail.layer_id;
          form.room_name = detail.room_name;
          form.rental_area = detail.rental_area;
          form.price_unit = detail.price_unit;
          form.price_unit_min = detail.price_unit_min;
          form.decoration = detail.decoration;
          form.house_type = detail.house_type;
          form.property_right = detail.property_right;
          form.status = detail.status;
          form.room_status_txt = detail.room_status_txt;
          form.tag_id_arr = detail.tag_id_arr || [];
          form.investment_conditions = detail.investment_conditions || "";
          form.investment_policy = detail.investment_policy || "";
          form.landlord_id = detail.landlord_id;
        });
    };
    const setModelRef = (state) => {
      for (let key in state) {
        if (form[key] != undefined) {
          form[key] = state[key];
        }
      }
    };

    // 房源标签
    const editVisible = ref(false);
    const addTag = () => {
      console.log("添加");
      editVisible.value = true;
    };
    const editTagClose = () => {
      editVisible.value = false;
    };
    const add = ref(0);
    const editSuccess = () => {
      editTagClose();
      industryList();
      add.value = 1;
    };
    // 行业分类
    const industryOptions = ref([]);
    const industryList = () => {
      request.get("/org", "/manage/taglib/house/all").then((res) => {
        if (props.id) {
          industryOptions.value = res.list.map((item) => {
            return {
              value: item.id,
              label: item.name,
              id: item.id,
            };
          });
          if (add.value == 1) {
            tag_id_arr.value.push(res.list[0].id);
          }
          return;
        }
        if (add.value == 1) {
          tag_id_arr.value.push(res.list[0].id);
        }
        industryOptions.value = res.list.map((item) => {
          return {
            value: item.id,
            label: item.name,
            id: item.id,
          };
        });
      });
    };

    // 招商状态
    const invitationOption = [
      {
        value: 1,
        label: "招商",
      },
      {
        value: 0,
        label: "不招商",
      },
    ];

    const cropSuccessImage = (data) => {
      images = data.map((item) => item.url);
    };
    const removeImageList = (data) => {
      images = data.map((item) => item.url);
    };

    // 图片
    const fileList = ref([]);
    let images = [];
    const handleUploadChange = (info) => {
      let resFileList = [...info.fileList];
      if (resFileList.length) {
        resFileList = resFileList.map((file) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;
              images.push(file.url);
            } else {
              message.warning(file.response.msg);
            }
          }
          return file;
        });
      } else {
        images = [];
      }
      fileList.value = resFileList;
    };

    // 上传视频
    const fileListVideo = ref([]);
    const handleChange = (info) => {
      if (info.file.status == "removed") {
        form.video = "";
        fileListVideo.value = [];
      }
      let resFileList = [...info.fileList];
      let result = resFileList.slice(-1);
      result = result[0];
      if (result && result.response) {
        if (result.response.code == 1000) {
          fileListVideo.value = resFileList.slice(-1);
          form.video = resFileList.slice(-1)[0].response.data.fileUrl;
        } else {
          message.warning(result.response.msg);
        }
      }
    };

    const beforeUpload = (file) => {
      const isLt2M = file.size / 1024 / 1024 <= 10;
      if (!isLt2M) {
        message.error("视频仅支持 10MB 以内");
      }

      return isLt2M;
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          state.edit_id = state.edit_id + 1;
          init();
          if (villageType.value === "village") {
            form.invitation_status = invitationOption[1].value;
          } else {
            form.invitation_status = invitationOption[0].value;
          }
        } else {
          resetFields();
          fileList.value = [];
          images = [];
          state.activeKey = "basic";
          state.edit_id = state.edit_id + 1;
        }
      }
    );

    onMounted(() => {
      state.edit_id = state.edit_id + 1;
      init();
      if (villageType.value === "village") {
        form.invitation_status = invitationOption[1].value;
      } else {
        form.invitation_status = invitationOption[0].value;
      }
    });
    onBeforeUnmount(() => {
      resetFields();
      fileList.value = [];
      images = [];
      state.activeKey = "basic";
      state.edit_id = state.edit_id + 1;
    });
    const dictName = computed(() => {
      return "请输入" + BLCOMMON.utils.L("报价");
    });
    const ListingStatusName = computed(() => {
      return "请输入" + BLCOMMON.utils.L("房源") + "状态";
    });
    const house_type_name = computed(() => {
      return "请输入" + BLCOMMON.utils.L("房源") + "类型";
    });
    const record_no_name = computed(() => {
      return "请输入" + BLCOMMON.utils.L("房源") + "备案号";
    });

    // 裁剪图片
    const cropSuccess = (link) => {
      form.extra_config.house = link[0].url;
    };
    // 移除图片
    const removeImage = () => {
      form.extra_config.house = "";
    };

    // 快速选择楼层
    const layerEditVisible = ref(false);
    const layerContent = ref({});

    const addLayer = () => {
      layerContent.value.villageId = form.village_id;
      layerContent.value.buildId = form.build_id;
      layerEditVisible.value = true;
    };
    const handleLayerEditSuccess = () => {
      layerEditVisible.value = false;
      getFloor(form.build_id);
    };

    const Selectcancel = (id , data) => {
      form.landlord_id = id;
    }

    const changeallowes = (id , data) => {
      form.landlord_id = id;
    }

    const init = () => {
      if (props.id) {
        getDetail();
      }
      getProjectList();
      getDecoration();
      industryList();
    };
    let state = reactive({
      activeKey: "basic",
      tabList: [
        {
          key: "basic",
          title: "基础信息",
        },
        {
          key: "invitation",
          title: "招商信息",
        },
        {
          key: "expend",
          title: "拓展信息",
        },
      ],
      ueditorEditorConfig: {
        UEDITOR_HOME_URL: utils.staticUeditorEditorPaths, // 访问 UEditor 静态资源的根路径，可参考常见问题1
        serverUrl: request.BASE_URL + "/public/system/uploadUEditor", // 服务端接口（这个地址是我为了方便各位体验文件上传功能搭建的临时接口，请勿在生产环境使用！！！）
        initialFrameHeight: 350,
        autoHeightEnabled: false,
        enableAutoSave: false,
        destroy: true,
      },
      editor: null,
      edit_id: 1,
      houseOwner: false,
      data: {},
    });
    const ready = (editor) => {
      state.editor = editor;
      console.log(state.editor, "state.editor");
    };

    const onRentalAreaBlur = () => {
      if (form.rental_area && Number(form.rental_area) > 0) {
        if (!form.charging_area || form.charging_area == 0) {
          form.charging_area = form.rental_area;
        }
        if (!form.build_area || form.build_area == 0) {
          form.build_area = form.rental_area;
        }
        if (!form.inside_area || form.inside_area == 0) {
          form.inside_area = form.rental_area;
        }
      }
    };
    return {
      ready,
      ...toRefs(state),
      tagArrChange,
      form,
      rules,
      projectList,
      validateInfos,
      buildingList,
      floorList,
      propertyRightList,
      DecorationList,
      ListingStatusList,
      HouseTypeList,
      onCancel,
      onClose,
      onSubmit,
      resetFields,
      validate,
      changeBuilding,
      changeVillageId,
      getFloor,
      title,
      tag_id_arr,
      industryOptions,
      addTag,
      editVisible,
      editSuccess,
      editTagClose,
      invitationOption,
      fileList,
      handleUploadChange,
      dictName,
      ListingStatusName,
      house_type_name,
      record_no_name,
      cropSuccess,
      removeImage,
      Selectcancel,
      changeallowes,

      cropperOptions: {
        autoCrop: true, //是否默认生成截图框
        // autoCropWidth: 200, //默认生成截图框宽度
        // autoCropHeight: 200, //默认生成截图框高度
        fixedBox: false, //是否固定截图框大小 不允许改变
        previewsCircle: false, //预览图是否是圆形
        title: "图片裁剪", //模态框上显示的标题
        imageUrl: "",
      },
      imgType: "testUp", //图片存储在oss上的上级目录名
      imgUrl: "", //上传图片所得到的地址
      imageCropper,
      imageCropperList,
      cropSuccessImage,
      removeImageList,
      handleChange,
      fileListVideo,
      beforeUpload,

      placeholderVillage: `请选择${BLCOMMON.utils.L("项目")}`,
      placeholderBuild: `请选择${BLCOMMON.utils.L("楼宇")}`,
      placeholderNumber: `请输入${BLCOMMON.utils.L("房源")}招商编号`,

      addLayer,
      layerContent,
      layerEditVisible,
      handleLayerEditSuccess,

      contractPriceUnitArr,
      isUnrealOptions,

      onRentalAreaBlur,
    };
  },
});

const isUnrealOptions = [
  {
    value: 0,
    label: "否",
  },
  {
    value: 1,
    label: "是",
  },
];
</script>

<style lang="less" scoped>
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}
input[type="number"] {
  -moz-appearance: textfield;
}
.Video {
  margin-top: 10px;
  color: #8d8d8d;
}
.icones {
  display: inline-block;
  height: 32px;
  line-height: 32px;
  width: 32px;
  text-align: center;
  color: #888787;
  cursor: pointer;
  border-top: 1px solid #d9d9d9;
  border-right: 1px solid #d9d9d9;
  border-bottom: 1px solid #d9d9d9;
}
</style>
